import os
import sys
import importlib.util
import json

# Dynamically add memory_systems to sys.path to import AgentMetadataDB
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
sys.path.insert(0, os.path.join(BASE_DIR, "memory_systems"))
sys.path.insert(0, os.path.join(BASE_DIR, "root_agent"))

import memory_systems.agent_metadata_db
import root_agent.llm

def _initialize_llm_client():
    try:
        return root_agent.llm.LLMInterface()
    except Exception as e:
        print(f"Error initializing LLMClient: {e}")
        return None

llm_client = _initialize_llm_client()

def set_agent_enabled_status(agent_name: str = None, enable: bool = True, description: str = None) -> dict:
    """在agent_metadata.json中设置特定代理的启用状态。
    如果未提供agent_name但提供了description，则将使用LLM选择代理。

    Args:
        agent_name (str): 要配置的代理的名称。如果提供了description，则为可选。
        enable (bool): True以启用代理，False以禁用它。
        description (str): 如果未提供agent_name，则帮助LLM选择代理的描述。可选。

    Returns:
        dict: 一个指示成功或失败以及消息的字典。
    """
    agent_db = memory_systems.agent_metadata_db.AgentInfoDB()

    if agent_name is None and description is not None:
        if not llm_client:
            return {"status": "failure", "message": "LLM client not initialized. Cannot select agent by description."
}
        all_agents = agent_db.get_all_agents(include_disabled=True)
        agent_list_str = "\n".join([f"- {name}: {info.get('description', 'No description')}" for name, info in all_agents.items()])

        prompt = f"""根据以下描述，从提供的Agent列表中选择最符合的Agent名称。
请只输出Agent的名称，不要包含任何解释性文字或Markdown格式。

描述: {description}

可用Agent列表:
{agent_list_str}

请选择一个Agent名称:
"""
        try:
            response = llm_client.generate_content(prompt)
            selected_agent_name = response.strip().split('\n')[0].strip()
            if selected_agent_name in all_agents:
                agent_name = selected_agent_name
            else:
                return {"status": "failure", "message": f"LLM selected an invalid agent: '{selected_agent_name}'. Please provide a more precise description or an exact agent name."
}
        except Exception as e:
            return {"status": "failure", "message": f"Error selecting agent with LLM: {e}"
}
    elif agent_name is None and description is None:
        return {"status": "failure", "message": "Either agent_name or description must be provided."
}

    if agent_name is None:
        return {"status": "failure", "message": "Agent name could not be determined."
}

    if enable:
        success = agent_db.enable_agent(agent_name)
        action = "enabled"
    else:
        success = agent_db.disable_agent(agent_name)
        action = "disabled"

    if success:
        return {"status": "success", "message": f"Agent '{agent_name}' successfully {action}."}
    else:
        return {"status": "failure", "message": f"Failed to {action} agent '{agent_name}'. It might not exist or cannot be disabled (e.g., rootagent)."}